#include "emfdrawable.h"

EmfDrawable::EmfDrawable()
{
    resetColor();
}

void EmfDrawable::addCoordinates(QPointF point)
{
    _emf.push_back(point);
}

QRectF EmfDrawable::getBoundingBox()
{
    QPointF maxLeftTop = _emf[0];
    QPointF maxRightBottom = _emf[0];
    QPointF point;
    for(int i=1; i<_emf.size(); i++)
    {
        point = _emf[i];
        if(point.x() < maxLeftTop.x())
        {
            maxLeftTop.setX(point.x());
        }
        if(point.y() < maxLeftTop.y())
        {
            maxLeftTop.setY(point.y());
        }
        if(point.x() > maxRightBottom.x())
        {
            maxRightBottom.setX(point.x());
        }
        if(point.y() > maxRightBottom.y())
        {
            maxRightBottom.setY(point.y());
        }
    }
    return QRectF(maxLeftTop, maxRightBottom);
}

void EmfDrawable::draw(CoodrsTransformer *coordsTransformer)
{
    glLineWidth(2);
    glBegin(GL_LINE_STRIP);
    for(int i=0; i<_emf.size(); i++)
    {
        glColor3f(_color.redF(), _color.greenF(), _color.blueF());

        QPointF coords = _emf[i];
        if(coordsTransformer)
        {
            coords = coordsTransformer->transform(coords);
        }
        glVertex2d(coords.x(), coords.y());
    }
    glEnd();
    glLineWidth(1);
}

bool EmfDrawable::isSelected(QPointF selectedPoint)
{
    QRectF boundary = getBoundingBox();    
    if(boundary.contains(selectedPoint))
    {
        for(int i=1; i<_emf.size(); i++)
        {
            QLineF line = QLineF(_emf[i-1], _emf[i]);
            if(_containsPoint(selectedPoint, line))
            {
                return true;
            }
        }
    }
    return false;
}

bool EmfDrawable::_containsPoint(QPointF point, QLineF line)
{
    double up = point.x() - line.p2().x();
    double down = line.p1().x() - line.p2().x();
    double p =  up/down;
    double y = p*line.p1().y() + (1 - p)*line.p2().y();
    if(p <= 1 && p >= 0 && abs(y - point.y()) <= POINT_DELTA)
    {
        return true;
    }
    return false;
}

qreal EmfDrawable::getValueByTime(qreal time)
{
    for(int i = 1; i < _emf.size(); i ++)
    {
        if(time >= _emf.value(i-1).x() &&  time <= _emf.value(i).x())
        {
            qreal A = (_emf.value(i).y()  -  _emf.value(i-1).y()) / ( _emf.value(i).x() - _emf.value(i-1).x() );
            qreal b = _emf.value(i-1).y() - A * _emf.value(i-1).x();
            return A*time + b;
        }
    }
    return 0.0;
}
